package com.cdvtc.fengchao.dao;

import com.cdvtc.fengchao.DBUtil;
import com.cdvtc.fengchao.model.Order;
import com.cdvtc.fengchao.model.OrderDetail;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class OrdersDAO {

    // 创建新订单
    public int createOrder(Order order) {
        String sql = "INSERT INTO orders (user_id, purchase_time, payment_status, total_amount) " +
                "VALUES (?, NOW(), '未支付', ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {

            pstmt.setInt(1, order.getUserId());
            pstmt.setDouble(2, order.getTotalAmount());

            int affectedRows = pstmt.executeUpdate();
            if (affectedRows > 0) {
                try (ResultSet rs = pstmt.getGeneratedKeys()) {
                    if (rs.next()) {
                        return rs.getInt(1); // 返回订单ID
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    // 添加订单详情
    public boolean addOrderDetails(OrderDetail detail) {
        String sql = "INSERT INTO order_details (order_id, product_id, quantity, total_price) " +
                "VALUES (?, ?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, detail.getOrderId());
            pstmt.setInt(2, detail.getProductId());
            pstmt.setInt(3, detail.getQuantity());
            pstmt.setDouble(4, detail.getTotalPrice());
            return pstmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取用户订单列表
    public List<Order> getOrdersByUserId(int userId) {
        List<Order> orders = new ArrayList<>();
        String sql = "SELECT * FROM orders WHERE user_id = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setInt(1, userId);
            try (ResultSet rs = pstmt.executeQuery()) {
                while (rs.next()) {
                    Order order = new Order();
                    order.setId(rs.getInt("id"));
                    order.setUserId(rs.getInt("user_id"));
                    order.setPurchaseTime(rs.getTimestamp("purchase_time"));
                    order.setPaymentStatus(rs.getString("payment_status"));
                    order.setTotalAmount(rs.getDouble("total_amount"));
                    orders.add(order);
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return orders;
    }
}

